<?php

/**
 * User Model
 *
 */
class Application_Model_User
{
    const DB_TABLE='users';
    const RESOURCE_NAME='user';
    
    protected $_data;
    protected $_role;
    
    /**
     * Constructor
     *
     * @param mixed $user
     */
    public function __construct($user=null)
    {
        $this->_role=new Application_Model_UserRoles();
        
        if (!empty($user) && (is_array($user) || (is_object($user) && ($user instanceof Zend_Db_Table_Row))))
        {
            $this->_init($user);
        } else 
        {
            $this->_init(array(
                'id' => 0,
                'login' => '',
                'password' => '',
                'email' => '',
                'nicename' => 'Guest',
                'role' => Application_Model_UserRoles::getDefaultRole(),
                'status' => 1
            ));
        } 
    }
    
    /**
     * Magic function
     *
     * @param string $var
     */
    public function __get($var)
    {
        return $this->_getData($var);
    }
    
    /**
     * Magic function
     *
     * @param string $var
     * @param mixed $val
     */
    public function __set($var,$val)
    {
        $this->_setData($var,$val);
    }
    
    /**
     * Magic function
     *
     * @param string $var
     */
    public function __unset($var)
    {
        if (array_key_exists($var,$this->_data))
        {
            unset($this->_data[$var]);
        }
    }
    
    /**
     * Magic function
     *
     * @param string $var
     * @return bool
     */
    public function __isset($var)
    {
        return array_key_exists($var,$this->_data);
    }
    
    /**
     * Magic function
     *
     * @return string
     */
    public function __toString()
    {
        return (string) !empty($this->nicename) ? $this->nicename : $this->login;
    }
    
    /**
     * Initializes user
     *
     * @param mixed $user
     */
    protected function _init($user)
    {
        foreach ($user as $var=>$val)
        {
            $this->_setData($var,$val);
        }
    }
    
    /**
     * Gets variable value
     *
     * @param string $var
     * @return mixed
     */
    protected function _getData($var)
    {
        $method='_getValue'.ucwords($var);
        
        if (method_exists($this,$method))
        {
            return $this->{$method}();
        }
        
        return null;
    }
    
    /**
     * Sets variable value
     *
     * @param string $var
     * @param mixed $val
     */
    protected function _setData($var,$val)
    {
        $method='_setValue'.ucwords($var);
        
        if (method_exists($this,$method))
        {
            $this->{$method}($val);
        }
    }

    /**
     * Returns user ID
     *
     * @return int
     */
    protected function _getValueId()
    {
        return (int) $this->_data['id'];
    }
    
    /**
     * Returns user login
     *
     * @return string
     */
    protected function _getValueLogin()
    {
        return (string) $this->_data['login'];
    }
    
    /**
     * Returns user password
     *
     * @return string
     */
    protected function _getValuePassword()
    {
        return (string) $this->_data['password'];
    }
    
    /**
     * Returns user E-Mail
     *
     * @return string
     */
    protected function _getValueEmail()
    {
        return (string) $this->_data['email'];
    }
    
    /**
     * Returns user full name
     *
     * @return string
     */
    protected function _getValueNicename()
    {
        if ($this->isBlocked()) return '#'.$this->id.' - '.$this->getStatus();
        
        return (string) $this->_data['nicename'];
    }
    
    /**
     * Returns user role
     *
     * @return string
     */
    protected function _getValueRole()
    {
        return (string) $this->_data['role'];
    }
    
    /**
     * Returns user status
     *
     * @return int
     */
    protected function _getValueStatus()
    {
        return (int) $this->_data['status'];
    }
    
    /**
     * Returns user meta data
     *
     * @return array
     */
    protected function _getValueMeta()
    {
        if ($this->isBlocked()) return array();
        
        $meta=array();
        
        if (!empty($this->_data['meta']))
        {
            try {
                $data=Zend_Registry::get('serializer')->unserialize($this->_data['meta']);
                if (is_array($data))
                {
                    $meta=$data;
                }
            } catch (Zend_Serializer_Exception $e) {}
        }
         
        return $meta;
    }
    
    /**
     * Sets user ID
     *
     * @param int $val
     */
    protected function _setValueId($val)
    {
        $this->_data['id']=(int) $val;
    }
    
    /**
     * Sets user login
     *
     * @param string $val
     */
    protected function _setValueLogin($val)
    {
        $this->_data['login']=(string) $val;
    }
    
    /**
     * Sets user password
     *
     * @param string $val
     */
    protected function _setValuePassword($val)
    {
        $this->_data['password']=(string) $val;
    }
    
    /**
     * Sets user E-Mail
     *
     * @param string $val
     */
    protected function _setValueEmail($val)
    {
        $this->_data['email']=(string) $val;
    }
    
    /**
     * Sets user full name
     *
     * @param string $val
     */
    protected function _setValueNicename($val)
    {
        $this->_data['nicename']=(string) $val;
    }
    
    /**
     * Sets user role if valid
     *
     * @param string $val
     */
    protected function _setValueRole($val)
    {
        $this->_data['role']=Application_Model_UserRoles::isValidRole($val) ? $val : Application_Model_UserRoles::getDefaultRole();
        
        $this->_role->setRoleId($this->_data['role']);
    }
    
    /**
     * Sets user status if valid
     *
     * @param int $val
     */
    protected function _setValueStatus($val)
    {
        $this->_data['status']=Application_Model_UserStatuses::isValidStatus($val) ? $val : Application_Model_UserStatuses::getDefaultStatus();
    }
    
    /**
     * Sets user meta data
     *
     * @param array $val
     */
    protected function _setValueMeta($val)
    {
        $data=$val;
        $meta=array();
        
        if (is_array($val))
        {
           try {
                $data=Zend_Registry::get('serializer')->serialize($val);
           } catch (Zend_Serializer_Exception $e) {}
        }

        $this->_data['meta']=$data;
    }
    
    /**
     * Returns password hash
     *
     * @param string $password
     * @return string
     */
    static function crypt_password($password)
    {
        return md5($password);
    }
    
    /**
     * Checks if user is registered
     *
     * @return bool
     */
    public function isRegistered()
    {
        return $this->_data['id'] > 0 ? true : false;
    }
    
    /**
     * Checks if user is active
     *
     * @return bool
     */
    public function isActive()
    {
        return $this->_data['status']==Application_Model_UserStatuses::getActiveStatus() ? true : false;
    }
    
    /**
     * Checks if user is not active yet
     *
     * @return bool
     */
    public function isNotActive()
    {
        return $this->_data['status']==Application_Model_UserStatuses::getDefaultStatus() ? true : false;
    }
    
    /**
     * Checks if user is blocked
     *
     * @return bool
     */
    public function isBlocked()
    {
        return $this->_data['status']==Application_Model_UserStatuses::getBlockedStatus() ? true : false;
    }
    
    /**
     * Checks if user is logged in
     *
     * @return bool
     */
    public function isLogged()
    {
        return $this->isRegistered() && $this->isActive() ? true : false;
    }
    
    /**
     * Returns an array with user data
     *
     * @return array
     */
    public function toArray()
    {
        return $this->_data;
    }
    
    /**
     * Returns role object
     *
     * @return object
     */
    protected function _getRole()
    {
        return $this->_role;
    }

    /**
     * Returns resource object
     *
     * @return object
     */
    protected function _getResource()
    {
        return Zend_Registry::get('resourcesObj');
    }
    
    /**
     * Checks user view permission for active resource
     * 
     * @param object $resource
     *
     * @return bool
     */
    public function canView(Application_Model_UserResources $resource = null)
    {
        $access=Zend_Registry::get('access');
        
        if (!empty($resource)) return $access->canView($this->_getRole(),$resource);
        
        return $access->canView($this->_getRole(),$this->_getResource());
    }
    
    /**
     * Checks user post permission for active resource
     *
     * @param object $resource
     * 
     * @return bool
     */
    public function canPost(Application_Model_UserResources $resource = null)
    {
        $access=Zend_Registry::get('access');
        
        if (!empty($resource)) return $access->canPost($this->_getRole(),$resource);
        
        return $access->canPost($this->_getRole(),$this->_getResource());
    }

    /**
     * Checks user manage permission for active resource
     *
     * @param object $resource
     * 
     * @return bool
     */
    public function canManage(Application_Model_UserResources $resource = null)
    {
        $access=Zend_Registry::get('access');
        
        if (!empty($resource)) return $access->canManage($this->_getRole(),$resource);
        
        return $access->canManage($this->_getRole(),$this->_getResource());
    }
    
    /**
     * Sets non active user role to default value
     *
     */
    public function blockNonActiveUser()
    {
        if (!$this->isLogged())
        {
            $this->_setValueRole(Application_Model_UserRoles::getDefaultRole());
        }
    }
    
    /**
     * Returns user role name
     *
     * @return string
     */
    public function getRole()
    {
        return Application_Model_UserRoles::getRoleName($this->_getValueRole());
    }
    
    /**
     * Returns user status name
     *
     * @return string
     */
    public function getStatus()
    {
        return Application_Model_UserStatuses::getStatusName($this->_getValueStatus());
    }
    
    /**
     * Returns user avatar filename
     *
     * @return string
     */
    public function getAvatar()
    {
        return !empty($this->meta['avatar']) ? $this->meta['avatar'] : '';
    }
    
    /**
     * Sets user avatar
     *
     * @param string $filename
     */
    public function setAvatar($filename)
    {
        $meta=$this->meta;
        $meta['avatar']=$filename;
        $this->meta=$meta;
    }
    
    /**
     * Returns user description
     *
     * @return string
     */
    public function getDescription()
    {
        return !empty($this->meta['description']) ? $this->meta['description'] : '';
    }
    
    /**
     * Sets user description
     *
     * @param string $text
     */
    public function setDescription($text)
    {
        $meta=$this->meta;
        $meta['description']=$text;
        $this->meta=$meta;
    }
}

